package org.example.service.impl;

import org.example.exception.CunstomAuthenticationException;
import org.example.model.LoginUserDetails;
import org.example.model.SysAuthorityEntity;
import org.example.model.SysUserEntity;
import org.example.service.SysAuthorityService;
import org.example.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Rommel
 * @version 1.0
 * @date 2023/6/14-18:07
 * @description TODO
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysAuthorityService authoritiesService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUserEntity sysUserEntity = sysUserService.selectByUsername(username);
        if(Objects.isNull(sysUserEntity)){
            throw new CunstomAuthenticationException("用户不存在！");
        }

        List<SysAuthorityEntity> authoritieList = authoritiesService.listByUsername(username);
        if(CollectionUtils.isEmpty(authoritieList)){
            throw new CunstomAuthenticationException("用户无权限！");
        }

        List<GrantedAuthority> grantedAuthorityList = authoritieList.stream().map(l->{
            return new SimpleGrantedAuthority(l.getAuthority());
        }).collect(Collectors.toList());

        return new LoginUserDetails(username,sysUserEntity.getPassword(),grantedAuthorityList,sysUserEntity.getId());
    }
}
